# -*- coding:utf-8 -*-

import pandas as pd
from pyecharts import Bar, Pie, Grid, Line, Polar, Geo
import time
import numpy as np
from collections import Counter
import operator
from seeting import testtime, testinterval


# 生成订单html
def orderhtml(data2):

    order_dict = dict(Counter(data2.ORDER))
    attr = [_ for _ in sorted(order_dict.keys())]
    values = [order_dict[key] for key in sorted(order_dict.keys())]
    order_amount = [round(sum(data2.AMOUNT[data2.ORDER == key])) for key in sorted(
        order_dict.keys())]

    per_order = np.array(order_amount) // np.array(values)

    pie = Pie("不同类别订单占比及均单价",)
    pie.add("订单数量", attr, values,
            radius=[45, 55], center=[30, 50], is_random=True,is_label_show=True)
    pie.add("订单金额", attr, order_amount,
            radius=[0, 20], center=[30, 50],is_label_show=True)

    bar = Bar("", height=720, width=1200, title_pos="65%")
    bar.add("不同类别订单单价", attr, per_order, mark_line=['average'],
            mark_point=["max","min"], legend_pos="80%",
            legend_orient="vertical", bar_category_gap='35%',
            is_label_show=True, line_color="blue")

    grid = Grid("", width=1600, height=800)
    grid.add(bar, grid_left="60%", grid_right="10%", grid_bottom="30%", grid_top="30%")
    grid.add(pie, grid_left="20%", grid_right="60%", grid_bottom="30%", grid_top="30%")
    grid.render(path='order.html')


# 当日总销售情况html
def salehtml(data2, searchtime):

    time_s = time.strftime('%Y-%m-%d %H:%M:%S')
    hour_dict = dict(Counter(data2.HOUR))

    # 如果还没有数据，就显示0
    for i in range(0, 24):
        if hour_dict.__contains__(i) == False:
            hour_dict[i] = 0

    hour_amount = [round(sum(data2.AMOUNT[data2.HOUR == i])) for i in range(0, 24)]
    attr = [str(_)+"点钟" for _ in range(0, 24)]
    values = [hour_dict[i] for i in sorted(hour_dict.keys())]
    line = Line(f"订单总量、总金额时刻折线图, 查询时间：{searchtime}")
    line.add("订单总量", attr, values, is_smooth=True, mark_line=["average"],
             mark_point=["max", "min"], is_label_show=True)
    line.add("订单总金额", attr, hour_amount, is_smooth=True,
             mark_point=["max", "min"], is_label_show=True)
    grid = Grid("", width=1600, height=800)
    grid.add(line, grid_left="20%", grid_right="20%", grid_bottom="20%", grid_top="30%")
    grid.render(path='sale.html')


# 不同IT市场html图
def typepolarhtml(data2):

    market_dict = dict(Counter(data2.MARKET))
    # 总计15个IT市场
    M_0 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[0]]))
    M_1 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[1]]))
    M_2 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[2]]))
    M_3 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[3]]))
    M_4 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[4]]))
    M_5 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[5]]))
    M_6 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[6]]))
    M_7 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[7]]))
    M_8 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[8]]))
    M_9 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[9]]))
    M_10 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[10]]))
    M_11 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[11]]))
    M_12 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[12]]))
    M_13 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[13]]))
    M_14 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[14]]))
    M_15 = dict(Counter(data2.ORDER[data2.MARKET == sorted(market_dict.keys())[15]]))

    mlist = [
        [M_0[item] for item in sorted(M_0.keys())],
        [M_1[item] for item in sorted(M_1.keys())],
        [M_2[item] for item in sorted(M_2.keys())],
        [M_3[item] for item in sorted(M_3.keys())],
        [M_4[item] for item in sorted(M_4.keys())],
        [M_5[item] for item in sorted(M_5.keys())],
        [M_6[item] for item in sorted(M_6.keys())],
        [M_7[item] for item in sorted(M_7.keys())],
        [M_8[item] for item in sorted(M_8.keys())],
        [M_9[item] for item in sorted(M_9.keys())],
        [M_10[item] for item in sorted(M_10.keys())],
        [M_11[item] for item in sorted(M_11.keys())],
        [M_12[item] for item in sorted(M_12.keys())],
        [M_13[item] for item in sorted(M_13.keys())],
        [M_14[item] for item in sorted(M_14.keys())],
        [M_15[item] for item in sorted(M_15.keys())]
    ]

    def percent(datalist):
        return [round(i/sum(datalist) * 100, 1) for i in datalist]
    # 为了看IT市场内部的订单比例，订单量没有意义，所有将数据均一化。
    rmlist = mlist
    for i in range(0, len(mlist)):
        rmlist[i] = percent(mlist[i])
    radius = sorted(M_0.keys())
    polar = Polar("各市场支付方式占比", width=1600, height=800, title_top="90%", title_text_size=40)
    marketlist = sorted(market_dict.keys())
    for i in range(0, len(rmlist)):
        polar.add(marketlist[i], rmlist[i], radius_data=radius, type='barRadius', is_stack=True)
    polar.render(path='typepolar.html')


# 销售量前后20的门店数据已经信息。
def storehtml(data2, searchtime):
    t_dict = dict(Counter(data2.INFO))

    # 将销售数据进行排序
    sorted_dict = sorted(t_dict.items(), key=operator.itemgetter(1))

    # 前20的门店信息
    top20 = sorted_dict[-20:]
    top20_a = [top20[i][0] for i in range(0, 20)]
    top20_v = [top20[i][1] for i in range(0, 20)]

    # 后20的门店信息
    tail20 = sorted_dict[0:20]
    tail20_a = [tail20[i][0] for i in range(0, 20)]
    tail20_v = [tail20[i][1] for i in range(0, 20)]

    # 距离查询时间testtime之内的订单量前20的门店的信息
    data3 = data2[data2.TIME < testtime]
    data4 = data3[(testtime - data3.TIME) < testinterval]
    store_20 = sorted(dict(Counter(data4.INFO)).items(), key=operator.itemgetter(1))[-20:]
    store20_a = [store_20[i][0] for i in range(0, 20)]
    store20_v = [store_20[i][1] for i in range(0, 20)]

    bar1 = Bar("当日截止查询时间总订单量前二十门店")
    bar1.add("", top20_a, top20_v, mark_line=["average"], mark_point=["max", "min"],
             bar_category_gap='35%')

    bar2 = Bar("当日截止查询时间总订单量末二十门店", title_top="33%")
    bar2.add("", tail20_a, tail20_v, mark_point=["max", "min"], bar_category_gap='35%')

    bar3 = Bar(f"十分钟之内订单量前二十门店，查询时间{searchtime}", title_top="66%")
    bar3.add("", store20_a, store20_v, mark_line=["average"], mark_point=["max", "min"],
             bar_category_gap='35%')

    grid = Grid(width=1600, height=800)
    grid.add(bar1, grid_top="5%", grid_bottom="75%", grid_left='20%', grid_right="20%")
    grid.add(bar2, grid_top="40%", grid_bottom="40%", grid_left='20%', grid_right="20%")
    grid.add(bar3, grid_top="75%", grid_bottom="5%", grid_left='20%', grid_right="20%")

    grid.render("topsale.html")


# 门店数据库最近一次心跳数据间隔监控图
def storemonitor(data2,searchtime):

    # testtime是当前查询时间
    data3 = data2[data2.TIME < testtime]
    # 按照time 列进行降序排序
    data3.sort_values("TIME", inplace=True, ascending=False)
    # 一个门店只保留最近一次出现的记录
    data4 = data3.drop_duplicates(subset=['INFO'], keep='first')
    # 将时间间隔以分钟的模式计算
    data4["DURATION"] = round((testtime - data4.TIME) / np.timedelta64(1, 'm'), 1)
    StoreInfo = data4[["INFO", "DURATION", "LONGITUDE", "LATITUDE"]]
    store = np.array(StoreInfo).tolist()
    value = [store[i][1] for i in range(0, len(store))]
    attr = [store[i][0] for i in range(0, len(store))]
    geo = Geo(f"KFC门店最近一次订单间隔,查询时间{searchtime}，单位分钟", "data from YumChina", title_pos="center", width=1800, height=900)
    for i in range(len(store)):
        geo.add_coordinate(store[i][0], store[i][2], store[i][3])
    geo.add("", attr, value, maptype='china', symbol_size=12, is_roam=False, type="scatter", is_visualmap=True,
            visual_range=[1, 10])
    geo.render("storemonitor.html")






